#include "timer.h"
#include "../dbg/dbg.h"

static struct timer_dev_t  timer_device;
struct utimer_date_t utimer_date;
uint32_t jiffies = 0;

/**
 * @brief 此设备守护进程
 * 
 * @param dev 
 * @param param 
 */
static void timer_daemon_process(struct timer_dev_t *dev ,void*param)
{
    
 //   dbg_print("daemon is running \r\n");
    jiffies++;
}
/**
* @brief 此函数应在定时器为500ms的定时器中调用
* 
*/
static void timer_callback_handler(struct timer_dev_t *dev ,void*param)
{
    uint8_t i = 0;
    if (dev==NULL)
    {
       // dbg_error("timer_callback_handler dev is NULL\r\n");
        return;
    }
    timer_daemon_process(dev, param);
    for (i=0;i<TIMER_INJECT_MAX;i++)
    {
        if(dev->timer_inject_callback[i]==NULL)
        {
          //  dbg_error("timer_callback_handler inject_callback  num[%d] is NULL\r\n",i);
            continue;
        }
        else
        {
            dev->timer_inject_callback[i](dev,param);
        }
    }
}


static int timer_set_inject(struct timer_dev_t *dev,void (*timer_inject_func)(struct timer_dev_t ,void*),uint8_t num)
{
    if (dev==NULL)
    {
       // dbg_error("timer_set_inject dev is NULL\r\n");
        return -1;
    }
    if (timer_inject_func==NULL)
    {
       // dbg_error("timer_set_inject timer_inject_func is NULL\r\n");
        return -2;
    }
    if(num >TIMER_INJECT_MAX)
    {
       // dbg_error("timer_set_inject is overrun ,MAX is %d, set val is %d\r\n",TIMER_INJECT_MAX,num);
        return -3;
    }
    (dev->timer_inject_callback)[num] = timer_inject_func;
    return 0;
}
uint32_t get_global_timer(void)
{
	return jiffies;
}
int timer_init(struct timer_dev_t **dev)
{
	  utimer_date.minsec  = 0;
    utimer_date.sec     = 0;
    utimer_date.min     = 0;
    utimer_date.hour    = 0; 
    utimer1_hal_init();
	  timer_device.timer_enable = timer1_hal_enable;
    timer_device.timer_callback = timer_callback_handler;
		timer_device.set_inject_callback = timer_set_inject;
	  timer_device.get_jiffies =get_global_timer;
    *dev = &timer_device;
    dbg_print("timer device initialized\r\n");
    return 0;
}
